<template> 
  <el-card class="form-container" shadow="never">
    <el-form :model="subject" :rules="rules" ref="subjectFrom" label-width="150px">

      <!-- <el-form-item label="分类：" prop="categoryId">
        <el-select
          v-model="subject.categoryId"
          @change="handlecateChange"
          placeholder="请选择分类">
          <el-option
            v-for="item in cateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="标题：" prop="title">
        <el-input v-model="subject.title"></el-input>
      </el-form-item>
      <el-form-item label="专题主图：" prop="pic">
        <single-upload v-model="subject.pic"></single-upload>
      </el-form-item>

      <!-- <el-form-item label="推荐：" prop="recommendStatus">
        <el-radio-group v-model="subject.recommendStatus">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item> -->


      <!-- <el-form-item label="画册：">
        <multi-upload v-model="selectProductPics"></multi-upload>
      </el-form-item> -->


      <!-- <el-form-item label="是否显示：">
        <el-radio-group v-model="subject.showStatus">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <!-- <el-form-item label="描述：" prop="description">
        <el-input
          :autoSize="true"
          v-model="subject.description"
          type="textarea"
          placeholder="请输入描述"></el-input>
      </el-form-item> -->

      <el-form-item label="内容：" prop="content">
        <el-tabs v-model="activeHtmlName" type="card">
          <el-tab-pane label="详情" name="pc">
            <tinymce :width="450" :height="300" v-model="subject.content"></tinymce>
          </el-tab-pane>
          <!-- <el-tab-pane label="移动端详情" name="mobile">
            <tinymce :width="595" :height="300" v-model="subject.content"></tinymce>
          </el-tab-pane> -->
        </el-tabs>
      </el-form-item>
      <!-- <el-form-item label="选择关联商品：" class="select-product">
        <el-select v-model="subject.relationProductIds" multiple collapse-tags filterable placeholder="请选择">
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <p class="tips">(可输入商品名称快速定位该商品)</p>
      </el-form-item> -->
      <el-form-item label="选择仓库：" required prop="depotId">
        <el-select v-model="subject.depotId">
          <el-option
            v-for="dept in depotList"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联商品" required>
        <el-table ref="productRelationTable" :data="subject.productList"
                style="width: 100%;" border v-if="subject.productList.length>0">
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="商品名称" width="276" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
         <el-table-column v-if="isEdit" label="操作" width="80" align="center">
          <template slot-scope="scope">
            <!-- <el-button size="mini"
                       type="text"
                       @click="handleUpdate(scope.$index, scope.row)">编辑
            </el-button> -->
            <el-button size="mini"
                       type="text"
                       @click="handleDeleteProduct(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
        </el-table>
      <el-button size="mini" class="btn-add" @click="handleSelectProduct()" style="margin-left: 20px">添加关联商品</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('subjectFrom')">提交</el-button>
        <el-button v-if="!isEdit" @click="resetForm('subjectFrom')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="选择商品" :visible.sync="selectDialogVisible" width="50%">
      <el-input v-model="dialogData.listQuery.keyword"
                style="width: 250px;margin-bottom: 20px"
                size="small"
                placeholder="商品名称搜索">
        <el-button slot="append" icon="el-icon-search" @click="handleSelectSearch()">点击搜索</el-button>
      </el-input>
      <el-table :data="dialogData.list"
                @selection-change="handleDialogSelectionChange" border>
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="商品图片" align="center">
          <template slot-scope="scope">
            <img style="max-width: 260px;max-height:60px;" :src="scope.row.pic" />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column label="货号" width="160" align="center">
          <template slot-scope="scope">NO.{{scope.row.productSn}}</template>
        </el-table-column>
        <el-table-column label="价格" width="120" align="center">
          <template slot-scope="scope">{{moneyIcon}}{{scope.row.price}}</template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleDialogSizeChange"
          @current-change="handleDialogCurrentChange"
          layout="prev, pager, next"
          :current-page.sync="dialogData.listQuery.pageNum"
          :page-size="dialogData.listQuery.pageSize"
          :page-sizes="[5,10,15]"
          :total="dialogData.total">
        </el-pagination>
      </div>
      <div style="clear: both;"></div>
      <div slot="footer">
        <el-button  size="small" @click="selectDialogVisible = false">取 消</el-button>
        <el-button  size="small" type="primary" @click="handleSelectDialogConfirm()">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<script>
  import {createSubject, updateSubject,
    getSubject,getBindedProductList,bindProducts,delbindedProducts} from '@/api/homeSubjectNow'
  // import {fetchList, deleteSubjectCategory} from '@/api/homeSubjectNow'
   import {fetchList as fetchProductList} from '@/api/product';
   import {fetchList as fetchDeptList} from '@/api/depository'
  import SingleUpload from '@/components/Upload/singleUpload'
  import Tinymce from '@/components/Tinymce'
  import MultiUpload from '@/components/Upload/multiUpload'
  const defaultSubject={
    name: '',
    productList:[],
  };
  export default {
    name: 'SubjectDetail',
    components:{SingleUpload, MultiUpload, Tinymce},
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        moneyIcon:process.env.MONEY_ICON,
        subject:Object.assign({}, defaultSubject),
        categoryName:'',
        album_pics:null,
        cateOptions:null,
        activeHtmlName: 'pc',
        rules: {
          name: [
            {required: true, message: '请输入名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
          pic: [
            {required: true, message: '请上传banner图', trigger: 'blur'}
          ],
          sort: [
            {type: 'number', message: '排序必须为数字'}
          ],
           depotId:[
            {required:true, message:'请选择仓库',trigger:"blur"}
          ]
        },
        dialogData:{
          list: null,
          total: null,
          multipleSelection:[],
          listQuery:{
            keyword: null,
            pageNum: 1,
            pageSize: 5,
            publishStatus:1,
            verifyStatus:1,
          },
        },
        //productList:[],//商品列表
        depotList:[],//仓库列表
        selectDialogVisible:false,//选择商品的弹窗
      }
    },
    computed: {
      //商品的主图和画册图片
      selectProductPics:{
        get:function () {
          let pics=[];
          if(this.albumPics===undefined||this.albumPics==null||this.albumPics===''){
            return pics;
          }
          let albumPics = this.albumPics.split(',');
          for(let i=0;i<albumPics.length;i++){
            pics.push(albumPics[i]);
          }
          return pics;
        },
        set:function (newValue) {
          if (newValue == null || newValue.length === 0) {
            this.albumPics = null;
          } else {
            this.albumPics = '';
            if (newValue.length > 1) {
              for (let i = 1; i < newValue.length; i++) {
                this.albumPics += newValue[i];
                if (i !== newValue.length - 1) {
                  this.albumPics += ',';
                }
              }
            }
          }
        }
      }
    },
    created() {
      this.getDepotList();
      if (this.isEdit) {
        getSubject(this.$route.query.id).then(response => {
          this.subject = response.data;
        });
        // getBindedProductList(this.$route.query.id).then(res=>{
        //   if( res.code === 200){
        //     this.subject.productList = res.data;
        //   }else{
        //     this.subject.productList = []
        //   }
        // })
      }else{
        this.subject = Object.assign({},defaultSubject);
      }
     // this.getCateList();
     
    },
    methods: {
      // getCateList() {
      //   fetchList({pageNum: 1, pageSize: 100}).then(response => {
      //     this.cateOptions = [];
      //   let brandList = response.data.records;
      //   for (let i = 0; i < brandList.length; i++) {
      //     this.cateOptions.push({label: brandList[i].name, value: brandList[i].id});
      //   }
      // });
      // },
      // handlecateChange(val) {
      //   let brandName = '';
      //   for (let i = 0; i < this.cateOptions.length; i++) {
      //     if (this.cateOptions[i].value === val) {
      //       brandName = this.cateOptions[i].label;
      //       break;
      //     }
      //   }

      //   this.categoryName = brandName;
      // },
      getDepotList(){
        let self = this;
        this.listLoading = true;
        fetchDeptList().then(({code,data})=>{
          if(code ==200 && data){
            this.depotList = data;
          }
        })
      },
       handleSelectProduct(){
        this.selectDialogVisible=true;
        this.getDialogList();
      },
      getDialogList(){
        fetchProductList(this.dialogData.listQuery).then(response=>{
          this.dialogData.list=response.data.list;
          this.dialogData.total=response.data.total;
        })
      },
      handleSelectSearch(){
        this.getDialogList();
      },
      handleDialogSizeChange(val) {
        this.dialogData.listQuery.pageNum = 1;
        this.dialogData.listQuery.pageSize = val;
        this.getDialogList();
      },
      handleDialogCurrentChange(val) {
        this.dialogData.listQuery.pageNum = val;
        this.getDialogList();
      },
      handleDialogSelectionChange(val){
        this.dialogData.multipleSelection = val;
      },
      handleSelectDialogConfirm(){
        if (this.dialogData.multipleSelection < 1) {
          this.$message({
            message: '请选择一条记录',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        if(this.isEdit){//编辑数据时，直接绑定相关产品、、新增数据时，需要把产品先记录下来，创建数据以后再进行绑定
          this.$confirm('确定进行绑定?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.bingingProducts(this.dialogData.multipleSelection);
          });
        }else{
          this.subject.productList = this.subject.productList.concat(this.dialogData.multipleSelection);
          this.$forceUpdate();
        }
       
        this.selectDialogVisible = false;//关闭弹窗
      },
      bingingProducts(selectProducts,isShowSucDia=true,subjectId=this.$route.query.id){
        let selectProductsIds = [];
        let len = selectProducts.length
        for (let i = 0; i < len; i++) {
          selectProductsIds.push(selectProducts[i].id)
        }
        bindProducts(subjectId,selectProductsIds).then(response=>{
          if(response.code ==200 && isShowSucDia){
              this.$message({
                type: 'success',
                message: '添加成功!'
              });
              //this.subject.productList = response.data;
              getBindedProductList(this.$route.query.id).then(res=>{
                this.subject.productList = res.data;
              })
              this.selectDialogVisible=false;
              this.dialogData.multipleSelection=[];
          }
        });
      },
      // handleEditDialogConfirm(){
      //   this.$confirm('是否要确认?', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //       updateFlashProductRelation(this.flashProductRelation.id,this.flashProductRelation).then(response => {
      //         this.$message({
      //           message: '修改成功！',
      //           type: 'success'
      //         });
      //         this.editDialogVisible =false;
      //         getBindedProductList(this.$route.query.id).then(res=>{
      //           this.subject.productList = res.data;
      //         })
      //       })
      //   })
      // },
      handleDeleteProduct(index,row){
        let deleteId = row.id;
        let ids = [];
        ids.push(row.id);
        // let productList = this.subject.productList;
        // let deleteIndex = productList.indexOf(row);
        // this.subject.productList.splice(deleteIndex,1);
        this.$confirm('是否删除商品', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delbindedProducts(this.$route.query.id,ids).then(res=>{
            if(res.code ==200){
              this.$message({
                message: '删除成功',
                type: 'success',
                duration:1000
              });
              getBindedProductList(this.$route.query.id).then(res=>{
                if( res.code === 200){
                  this.subject.productList = res.data;
                }else{
                  this.subject.productList = []
                }
              })
            }
          })
        })
      },
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.subject.categoryName=this.categoryName;
              this.subject.album_pics=this.album_pics;
              //this.bingingProducts(this.subject.productList,false);
              if (this.isEdit) {
                updateSubject(this.$route.query.id, this.subject).then(response => {
                  this.$refs[formName].resetFields();
                  this.$message({
                    message: '修改成功',
                    type: 'success',
                    duration:1000
                  });
                  this.$router.back();
                });
              } else {
                createSubject(this.subject).then(response => {
                  if(response.code ==200){
                    this.bingingProducts(this.subject.productList,false,response.data);
                    this.$refs[formName].resetFields();
                    this.subject = Object.assign({},defaultSubject);
                    this.$message({
                      message: '提交成功',
                      type: 'success',
                      duration:1000
                    });
                  }
                  
                this.$router.back();
                });
              }
            });

          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.subject = Object.assign({},defaultSubject);
      },
    }
  }
</script>
<style>
</style>